package com.hj.dapp.business.menu.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hj.dapp.business.menu.mapper.MenuMapper;
import com.hj.dapp.business.menu.model.Menu;
import com.hj.dapp.business.menu.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;

import static com.hj.dapp.common.constant.DictEnum.DIR_TYPE;
import static com.hj.dapp.common.constant.DictEnum.NORMAL_FLAG;

/**
 * @author 胡奥程
 * @version 1.0
 * @date 2023/12/30
 */
@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public List<Menu> getMenuByUser(Principal principal) {
        return menuMapper.getMenuByUser(principal.getName());
    }

    @Override
    public void saveMenu(Menu menu, Principal principal) {
        //如果没有序号，设置默认值
        if (ObjectUtils.isEmpty(menu.getOrderNum())) {
            QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("type", menu.getType());
            //如果不是目录
            if (!DIR_TYPE.getValue().equals(menu.getType())) {
                queryWrapper.eq("parent_id", menu.getParentId());
            }
            Long sort = menuMapper.selectCount(queryWrapper);
            sort++;
            menu.setOrderNum(sort.intValue());
        }

        menu.setCreateBy(principal.getName());
        menu.setCreateTime(LocalDateTime.now());
        menu.setDelFlag(NORMAL_FLAG.getValue());
        menuMapper.insert(menu);
    }

    @Override
    public List<Menu> getAllMenu() {
        return menuMapper.getAllMenu();
    }

}
